package cn.zebra.dev.shop.module.after.controller;

import cn.zebra.dev.common.restful.Result;
import cn.zebra.dev.ibatis.plus.utils.PageUtils;
import cn.zebra.dev.member.module.login.service.SecurityMemberService;
import cn.zebra.dev.member.module.member.entity.MemberEntity;
import cn.zebra.dev.member.module.member.service.MemberService;
import cn.zebra.dev.other.module.shopAfter.entity.ShopAfterEntity;
import cn.zebra.dev.other.module.shopAfter.service.ShopAfterService;
import cn.zebra.dev.shop.module.after.dto.AfterDTO;
import cn.zebra.dev.shop.module.after.vo.AdminAfterVO;
import cn.zebra.dev.shop.module.after.vo.AfterIdVO;
import cn.zebra.dev.shop.module.after.vo.AfterVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(tags = "店铺售后管理")
@RequestMapping("/shopAfter")
public class ShopAfterController {

    @Autowired
    private ShopAfterService shopAfterService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private SecurityMemberService securityMemberService;


    @GetMapping("/shopList/{shopId}")
    @ApiOperation("店铺售后列表(可选择0 同意处理，1 待处理进行查询,2 拒绝处理，若没有选择默认查询全部)")
    public Result<PageUtils<AfterDTO>> list(
            @PathVariable Long shopId,
            @RequestParam(value = "state",required = false)Long state,
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page) {
        Map<String, Object> params = new HashMap<>();
        params.put("shopId",shopId);
        params.put("limit", limit);
        params.put("page", page);
        params.put("state", state);
        PageUtils<ShopAfterEntity> pageUtils = shopAfterService.findPageByShopId(params);
        PageUtils<AfterDTO> data = new PageUtils<>(pageUtils);
        List<ShopAfterEntity> list = pageUtils.getList();
        if (list.size() > 0) {
            List<AfterDTO> dtoList = new LinkedList<>();
            List<Long> memberIds = list.stream().map(ShopAfterEntity::getUserId).collect(Collectors.toList());
            List<MemberEntity> memberEntities=memberService.findByIds(memberIds);
            list.forEach(entity -> {
                AfterDTO dto = new AfterDTO();
                BeanUtils.copyProperties(entity, dto);
                Optional<MemberEntity> memberEntityOptional = memberEntities.stream().filter(memberEntity -> memberEntity.getId().equals(entity.getUserId())).findAny();
                if(memberEntityOptional.isPresent()){
                    MemberEntity memberEntity = memberEntityOptional.get();
                    dto.setMemberName(memberEntity.getMemberName());
                    dto.setPhone(memberEntity.getPhone());
                }
                dtoList.add(dto);
            });
            data.setList(dtoList);
        }
        return Result.success(data);
    }


    @GetMapping("/userList/{userId}")
    @ApiOperation("用户售后列表(可选择0 同意处理，1 待处理进行查询,2 拒绝处理，若没有选择默认查询全部)")
    public Result<PageUtils<AfterDTO>> userList(
            @PathVariable Long userId,
            @RequestParam(value = "state",required = false)Long state,
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId",userId);
        params.put("limit", limit);
        params.put("page", page);
        params.put("state", state);
        PageUtils<ShopAfterEntity> pageUtils = shopAfterService.findPageByUserId(params);
        PageUtils<AfterDTO> data = new PageUtils<>(pageUtils);
        List<ShopAfterEntity> list = pageUtils.getList();
        if (list.size() > 0) {
            List<AfterDTO> dtoList = new LinkedList<>();
            List<Long> memberIds = list.stream().map(ShopAfterEntity::getUserId).collect(Collectors.toList());
            List<MemberEntity> memberEntities=memberService.findByIds(memberIds);
            list.forEach(entity -> {
                AfterDTO dto = new AfterDTO();
                BeanUtils.copyProperties(entity, dto);
                Optional<MemberEntity> memberEntityOptional = memberEntities.stream().filter(memberEntity -> memberEntity.getId().equals(entity.getUserId())).findAny();
                if(memberEntityOptional.isPresent()){
                    MemberEntity memberEntity = memberEntityOptional.get();
                    dto.setMemberName(memberEntity.getMemberName());
                    dto.setPhone(memberEntity.getPhone());
                }
                dtoList.add(dto);
            });
            data.setList(dtoList);
        }
        return Result.success(data);
    }

    @PostMapping("/save")
    @ApiOperation("店铺售后申请")
    public Result save(@Valid @RequestBody AfterVO vo) {
//        ValidatorUtils.validateEntity(vo);
        ShopAfterEntity entity = new ShopAfterEntity();
        BeanUtils.copyProperties(vo,entity);
        entity.setCreateTime(LocalDateTime.now());
        entity.setState(1L);
        entity.setUserId(securityMemberService.getMemberId());
        if(shopAfterService.save(entity)){
            return Result.success("申请已提交,请等待商家回复！");
        }
        return Result.success("申请提交失败!");
    }


    @PostMapping("/update/{id}")
    @ApiOperation("店铺售后处理")
    public Result update(@PathVariable Long id,@Valid @RequestBody AdminAfterVO vo) {
        ShopAfterEntity entity = new ShopAfterEntity();
        BeanUtils.copyProperties(vo,entity);
        if(!shopAfterService.update(entity,"id={0}",id)){
            return Result.success("操作失败!");
        }
        return Result.success("操作成功!");
    }




}
